package com.qf.shoppingproduct.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qf.shoppingproduct.entity.Product;
import com.qf.shoppingproduct.mapper.ProductMapper;
import entity.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    ProductMapper productMapper;

    @GetMapping("/all")
    public ResultData all() {
        QueryWrapper<Product> qw = new QueryWrapper<>();
        List<Product> products = productMapper.selectList(qw);
        return new ResultData<List>(true,products);
    }

//    @GetMapping("/{id}")
//    public ResultData getOne(@PathVariable(value = "id") Integer id) {
//        QueryWrapper<Product> qw = new QueryWrapper<>();
//        qw.eq("id", id);
//        Product product = productMapper.selectOne(qw);
//        return new ResultData(true,product);
//    }

    @GetMapping("/{id}")
    public Product getOne(@PathVariable(value = "id") Integer id) {
        QueryWrapper<Product> qw = new QueryWrapper<>();
        qw.eq("id", id);
        Product product = productMapper.selectOne(qw);
        return product;
    }

    @GetMapping("/decrease")
    public ResultData decrease(@PathVariable(value = "id") Integer id) {
        QueryWrapper<Product> qw = new QueryWrapper<>();
        qw.eq("id", id);
        Product product = productMapper.selectOne(qw);
        product.setInventory(product.getInventory() - 1);
        UpdateWrapper<Product> up = new UpdateWrapper<>();
        qw.eq("id", id);
        productMapper.update(product, up);
        return new ResultData<Object>(true,product);
    }

    /**
     * 库存减少
     * @param product
     * @return
     */
    @PostMapping("/reduce")
    public ResultData reduceInventory(@RequestBody Product product) {
        QueryWrapper<Product> qw = new QueryWrapper<>();
        qw.eq("id", product.getId());
        Product p = productMapper.selectOne(qw);
        
        return new ResultData<Object>(true,product);
    }
}
